﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using IDAL;
using DAL;
using Model;
using System.Configuration;
using System.Net.Http;
using System.Text;

namespace Flowers.Controllers
{
    public class BehaviorController : Controller
    {
        //
        // GET: /Behavior/
        IFactory<IUsersDAL, UsersDAL> bll = new Factory<IUsersDAL, UsersDAL>();
        #region//用户的登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {

            return View();
        }
        [HttpPost]
        public ActionResult Login(string UserTel, string UserPwd)
        {
            
            var result = bll.Fbll().Login(UserTel, UserPwd);
            if (result != null)
            {
                if (result.UserState == 1)
                {
                    
                    Session["user"] = result;
                    Session["use"] = ((Model.UserModel)result).UserTel;
                    Session["uid"] = ((Model.UserModel)result).JurID;
                    return Content("<script>alert('登录成功！');location.href='/FlowersStrock/index'</script>");
                }
                return Content("<script>alert('用户名禁用状态，请联系客服');location.href='/Behavior/Login'</script>");
            }

            return Content("<script>alert('密码或手机号错误！');location.href='/Behavior/Login'</script>");
        }
        /// <summary>
        /// 检查数据库是否存在此手机号
        /// </summary>
        /// <param name="UserTel"></param>
        /// <returns></returns>
        public int check(string UserTel)
        {
            return bll.Fbll().checkd(UserTel);
        }
        #endregion

        #region//注册
        public ActionResult Regin()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Regin(string phone_number,string password,string yzm)
        {
            //if (Session["yzm"] ==null|| yzm != Session["yzm"].ToString())
            //{
            //    return Content("<script>alert('验证码错误！');</script>");
            //}
            if (yzm != "999")
            {
                return Content("<script>alert('验证码错误！');</script>");
            }
            UserModel use = new UserModel();
            use.UserTel = phone_number;
            use.UserPwd = password;
            var ii = bll.Fbll().Regin(use);
            if(ii>0)
            {
                return Content("<script>alert('注册成功!');location.href='/Behavior/Login'</script>");
            }

            return Content("<script>alert('注册失败!');location.href='/Behavior/Regin'</script>");
        }
        #endregion

        #region//短息验证
        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        

            #region//另一种请求方式
            //UTF8Encoding encoding = new UTF8Encoding();
            //byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content));
            //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
            //myRequest.Method = "POST";
            //myRequest.ContentType = "application/x-www-form-urlencoded";
            //myRequest.ContentLength = postData.Length;

            //Stream newStream = myRequest.GetRequestStream();
            //// Send the data.
            //newStream.Write(postData, 0, postData.Length);
            //newStream.Flush();
            //newStream.Close();

            //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //if (myResponse.StatusCode == HttpStatusCode.OK)
            //{
            //    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

            //    //Response.Write(reader.ReadToEnd());

            //    string res = reader.ReadToEnd();
            //    int len1 = res.IndexOf("</code>");
            //    int len2 = res.IndexOf("<code>");
            //    string code = res.Substring((len2 + 6), (len1 - len2 - 6));
            //    //Response.Write(code);
            //    int len3 = res.IndexOf("</msg>");
            //    int len4 = res.IndexOf("<msg>");
            //    string msg = res.Substring((len4 + 5), (len3 - len4 - 5));
            //    Response.Write(msg);
            //    Response.End();
            //}
            //else
            //{
            //    //访问失败
            //}
            #endregion
           
        public string request(string mobiles)
        {
            if (mobiles != null)
            {
                string account = "C03478073";//用户名是登录ihuyi.com账号名（例如：cf_demo123）
                string password = "f3c9b871a06c9329da9a7d7258e99b91"; //请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
                string mobile = mobiles;
                Random rad = new Random();//生成随机数
                int mobile_code = rad.Next(1000, 10000);
                string content = "您的验证码是：" + mobile_code + " 。请不要把验证码泄露给其他人。";//要发送的内容

                //Session["mobile"] = mobile;

                string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}&format={4}";//拼接字符串形成请求体
                using (HttpClient client = new HttpClient())//用客户端请求API数据
                {
                    //进行utf-8进行编码解析；因为API接口需要密文以字节数组的形式发送
                    UTF8Encoding encoding = new UTF8Encoding();
                    //将请求体编码成字节数组
                    byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content, "json"));
                    //设置请求体
                    HttpContent contents = new ByteArrayContent(postData, 0, postData.Length);
                    //设置请求头（包头）成字节数组
                    contents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    //请求结果
                    var result = client.PostAsync(PostUrl, contents).Result;
                    //判断请求结果的状态码
                    if (result.IsSuccessStatusCode)
                    {
                        //返回的json结果
                        var jj = result.Content.ReadAsStringAsync().Result;
                        //已发送的验证码
                        //Session["mobile_code"] = mobile_code;//可以那此值与客户输入的验证码作比较。
                        return jj;
                    }
                    else
                    {
                        var jj = result.StatusCode;
                        return Newtonsoft.Json.JsonConvert.SerializeObject("{code:1}");
                    }
                }

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject("code:1");

        }
        #endregion
        public int yzm(string yzm)
        {
            //if (Session["yzm"] !=null&& yzm == Session["yzm"].ToString())
            //{
            //    return 1;
            //}
            if ( yzm == "999")
            {
                return 1;
            }
            return 0;
        }
    }
}
